from flask import Blueprint, request, jsonify
from models import db, UserHistory, LLMHistory, SearchHistory
from utils.text_auth import token_required
import json

history_bp = Blueprint('history', __name__)

@history_bp.route('/history', methods=['POST'])
@token_required
def save_history(current_user):
    """
    保存历史记录
    请求体：{
      history_uid: str,  // 前端ID
      type: 'retrieve'|'llm',
      route_name: str,
      summary: str,
      snapshot: Object,  // 任意JSON
      user_id?: number   // 可选
    }
    """
    data = request.get_json(force=True)
    history_uid = data.get('history_uid')
    record_type = data.get('type')
    route_name = data.get('route_name')
    summary = data.get('summary', '')
    snapshot = data.get('snapshot') or {}

    # 使用当前认证用户ID，而不是从请求体中获取
    user_id = current_user.id

    if not history_uid or record_type not in ('retrieve', 'llm') or not route_name:
        return jsonify({'status': 'error', 'message': '参数不完整'}), 400

    try:
        existed = UserHistory.query.filter_by(history_uid=history_uid).first()
        if existed:
            # 已存在则忽略或更新摘要/快照，这里选择更新
            existed.summary = summary or existed.summary
            existed.snapshot_json = json.dumps(snapshot, ensure_ascii=False)
            db.session.commit()
            return jsonify({'status': 'success', 'data': {'history_uid': history_uid}})

        record = UserHistory(
            history_uid=history_uid,
            user_id=user_id,
            type=record_type,
            route_name=route_name,
            summary=summary or '历史记录',
            snapshot_json=json.dumps(snapshot, ensure_ascii=False)
        )
        db.session.add(record)
        db.session.commit()
        return jsonify({'status': 'success', 'data': {'history_uid': history_uid}})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500

@history_bp.route('/history', methods=['GET'])
@token_required
def list_history(current_user):
    """
    获取历史记录列表（按时间倒序）
    查询参数：?limit=100
    """
    limit = min(int(request.args.get('limit', 100)), 500)
    q = UserHistory.query.filter_by(user_id=current_user.id)
    records = q.order_by(UserHistory.created_at.desc()).limit(limit).all()
    items = [{
        'history_uid': r.history_uid,
        'type': r.type,
        'route_name': r.route_name,
        'summary': r.summary,
        'timestamp': int(r.created_at.timestamp() * 1000),
    } for r in records]
    return jsonify({'status': 'success', 'data': {'items': items}})

@history_bp.route('/history/<history_uid>', methods=['GET'])
def get_history(history_uid):
    """
    获取历史快照详情
    """
    r = UserHistory.query.filter_by(history_uid=history_uid).first()
    if not r:
        return jsonify({'status': 'error', 'message': 'not found'}), 404
    try:
        snapshot = json.loads(r.snapshot_json)
    except Exception:
        snapshot = None
    return jsonify({'status': 'success', 'data': {
        'history_uid': r.history_uid,
        'type': r.type,
        'route_name': r.route_name,
        'summary': r.summary,
        'timestamp': int(r.created_at.timestamp() * 1000),
        'snapshot': snapshot
    }})

@history_bp.route('/history/<history_uid>', methods=['DELETE'])
def delete_history(history_uid):
    """
    删除历史记录
    """
    r = UserHistory.query.filter_by(history_uid=history_uid).first()
    if not r:
        return jsonify({'status': 'success'})  # 幂等
    try:
        db.session.delete(r)
        db.session.commit()
        return jsonify({'status': 'success'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500


# ==================== LLM历史记录API ====================

@history_bp.route('/llm-history', methods=['POST'])
@token_required
def save_llm_history(current_user):
    """
    保存LLM对话历史记录
    
    请求体：
    {
        prompt: str,           // 用户输入
        response: str,         // 模型输出
        model: str,            // 模型名称，默认'qwen-turbo'
        input_length: int,     // 输入长度
        output_length: int,    // 输出长度
        session_state: str     // 对话完整状态序列化（可选）
    }
    """
    try:
        data = request.get_json(force=True)
        prompt = data.get('prompt', '').strip()
        response = data.get('response', '').strip()
        
        if not prompt or not response:
            return jsonify({'status': 'error', 'message': 'prompt和response不能为空'}), 400
        
        record = LLMHistory(
            user_id=current_user.id,
            prompt=prompt,
            response=response,
            model=data.get('model', 'qwen-turbo'),
            input_length=data.get('input_length', len(prompt)),
            output_length=data.get('output_length', len(response)),
            session_state=json.dumps(data.get('session_state', {}), ensure_ascii=False) if data.get('session_state') else None
        )
        db.session.add(record)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'data': {
                'id': record.id,
                'created_at': record.created_at.isoformat() if record.created_at else None
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500


@history_bp.route('/llm-history', methods=['GET'])
@token_required
def list_llm_history(current_user):
    """
    获取当前用户的LLM历史记录列表（按时间倒序）
    
    查询参数：
        limit: int,  // 返回记录数，默认100，最大500
    """
    try:
        limit = min(int(request.args.get('limit', 100)), 500)
        records = LLMHistory.query.filter_by(user_id=current_user.id)\
            .order_by(LLMHistory.created_at.desc())\
            .limit(limit).all()
        
        items = [{
            'id': r.id,
            'prompt': r.prompt,
            'response': r.response,
            'model': r.model,
            'input_length': r.input_length,
            'output_length': r.output_length,
            'session_state': json.loads(r.session_state) if r.session_state else None,
            'created_at': r.created_at.isoformat() if r.created_at else None,
            'timestamp': int(r.created_at.timestamp() * 1000) if r.created_at else 0
        } for r in records]
        
        return jsonify({'status': 'success', 'data': {'items': items}})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


@history_bp.route('/llm-history/<int:history_id>', methods=['GET'])
@token_required
def get_llm_history(current_user, history_id):
    """
    获取单条LLM历史记录详情
    """
    try:
        record = LLMHistory.query.filter_by(id=history_id, user_id=current_user.id).first()
        if not record:
            return jsonify({'status': 'error', 'message': '记录不存在'}), 404
        
        return jsonify({
            'status': 'success',
            'data': {
                'id': record.id,
                'prompt': record.prompt,
                'response': record.response,
                'model': record.model,
                'input_length': record.input_length,
                'output_length': record.output_length,
                'session_state': json.loads(record.session_state) if record.session_state else None,
                'created_at': record.created_at.isoformat() if record.created_at else None,
                'timestamp': int(record.created_at.timestamp() * 1000) if record.created_at else 0
            }
        })
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


@history_bp.route('/llm-history/<int:history_id>', methods=['DELETE'])
@token_required
def delete_llm_history(current_user, history_id):
    """
    删除LLM历史记录
    """
    try:
        record = LLMHistory.query.filter_by(id=history_id, user_id=current_user.id).first()
        if not record:
            return jsonify({'status': 'success'})  # 幂等
        
        db.session.delete(record)
        db.session.commit()
        return jsonify({'status': 'success'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500


# ==================== 检索历史记录API ====================

@history_bp.route('/search-history', methods=['POST'])
@token_required
def save_search_history(current_user):
    """
    保存数据检索历史记录
    
    请求体：
    {
        keyword: str,          // 检索关键词
        search_type: str,      // 搜索类型，'simple'或'advanced'
        lang1: str,           // 源语言（可选）
        lang2: str,           // 目标语言（可选）
        threshold: float,     // 相似度阈值
        result_count: int,    // 结果数量
        page_state: object    // 序列化页面完整状态（可选）
    }
    """
    try:
        data = request.get_json(force=True)
        keyword = data.get('keyword', '').strip()
        
        if not keyword:
            return jsonify({'status': 'error', 'message': 'keyword不能为空'}), 400
        
        record = SearchHistory(
            user_id=current_user.id,
            keyword=keyword,
            search_type=data.get('search_type', 'simple'),
            lang1=data.get('lang1'),
            lang2=data.get('lang2'),
            threshold=float(data.get('threshold', 0.1)),
            result_count=int(data.get('result_count', 0)),
            page_state=json.dumps(data.get('page_state', {}), ensure_ascii=False) if data.get('page_state') else None
        )
        db.session.add(record)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'data': {
                'id': record.id,
                'created_at': record.created_at.isoformat() if record.created_at else None
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500


@history_bp.route('/search-history', methods=['GET'])
@token_required
def list_search_history(current_user):
    """
    获取当前用户的检索历史记录列表（按时间倒序）
    
    查询参数：
        limit: int,  // 返回记录数，默认100，最大500
    """
    try:
        limit = min(int(request.args.get('limit', 100)), 500)
        records = SearchHistory.query.filter_by(user_id=current_user.id)\
            .order_by(SearchHistory.created_at.desc())\
            .limit(limit).all()
        
        items = [{
            'id': r.id,
            'keyword': r.keyword,
            'search_type': r.search_type,
            'lang1': r.lang1,
            'lang2': r.lang2,
            'threshold': r.threshold,
            'result_count': r.result_count,
            'page_state': json.loads(r.page_state) if r.page_state else None,
            'created_at': r.created_at.isoformat() if r.created_at else None,
            'timestamp': int(r.created_at.timestamp() * 1000) if r.created_at else 0
        } for r in records]
        
        return jsonify({'status': 'success', 'data': {'items': items}})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


@history_bp.route('/search-history/<int:history_id>', methods=['GET'])
@token_required
def get_search_history(current_user, history_id):
    """
    获取单条检索历史记录详情
    """
    try:
        record = SearchHistory.query.filter_by(id=history_id, user_id=current_user.id).first()
        if not record:
            return jsonify({'status': 'error', 'message': '记录不存在'}), 404
        
        return jsonify({
            'status': 'success',
            'data': {
                'id': record.id,
                'keyword': record.keyword,
                'search_type': record.search_type,
                'lang1': record.lang1,
                'lang2': record.lang2,
                'threshold': record.threshold,
                'result_count': record.result_count,
                'page_state': json.loads(record.page_state) if record.page_state else None,
                'created_at': record.created_at.isoformat() if record.created_at else None,
                'timestamp': int(record.created_at.timestamp() * 1000) if record.created_at else 0
            }
        })
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


@history_bp.route('/search-history/<int:history_id>', methods=['DELETE'])
@token_required
def delete_search_history(current_user, history_id):
    """
    删除检索历史记录
    """
    try:
        record = SearchHistory.query.filter_by(id=history_id, user_id=current_user.id).first()
        if not record:
            return jsonify({'status': 'success'})  # 幂等
        
        db.session.delete(record)
        db.session.commit()
        return jsonify({'status': 'success'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500

